import React, { useState } from 'react';

type Solution = {
  step: string | number;
  method: string;
  description: string;
};

type TextResponse = {
  name: string;
  solutions: Solution[];
};

export const TextQA: React.FC = () => {
  const [prompt, setPrompt] = useState('');
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<TextResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setData(null);
    try {
      const res = await fetch('/api/get_text_response', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || '请求失败');
      setData(json as TextResponse);
    } catch (err: any) {
      setError(err.message || '未知错误');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="card">
      <h2>文字问答</h2>
      <form onSubmit={onSubmit} className="form">
        <textarea
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder="描述病虫害，例如：番茄早疫病防治方案"
          rows={4}
        />
        <button type="submit" disabled={!prompt || loading}>
          {loading ? '请求中...' : '提交'}
        </button>
      </form>

      {error && <div className="error">{error}</div>}

      {data && (
        <div className="result">
          <div className="result-header">
            <span className="tag">病虫害</span>
            <h3>{data.name}</h3>
          </div>
          <ol className="steps">
            {data.solutions?.map((s, idx) => (
              <li key={idx}>
                <div className="step-num">第{s.step}步</div>
                <div className="step-body">
                  <div className="method">{s.method}</div>
                  <div className="desc">{s.description}</div>
                </div>
              </li>
            ))}
          </ol>
        </div>
      )}
    </div>
  );
};

